import React, { useState, useEffect, useMemo } from 'react';
import { get_fix, get_ck, load_col, load_wtype } from './cmd';
import { loc, ColView, HandView, obj_str, no_del, is_empty, Chip, PanelFind, filter_row, obj_int, MUser, MLink, MCmd, useCmd,
    useHigh, KFile, Btn, GridTable } from 'sui';
import { BindUser } from './user';
import { BindEquip } from './equip';
import { useAccess } from 'cache';

const StationView = () => {
    const [wtype, setWtype] = useState();
    const [col, setCol] = useState();
    const [high] = useHigh(140, 100);
    const umd = useCmd("station/list", null, {count: true});
    const [no_acc] = useAccess();

    useEffect(() => {
        load_wtype(setWtype);
        load_col(setCol);
    }, []);

    const getRow = useMemo(() => {
        const lst = ["sn", "name", "tp"];
        return filter_row(umd.value, lst, umd.filter);
    }, [umd.value, umd.filter]);

    const hImport = (val) => {
        if (is_empty(col)) {
            alert(loc("l_686"));
            return;
        }

        if (is_empty(val)) {
            alert(loc("l_276"));
            return;
        }

        umd.update("station/madd", {v: val});
    };

    const hCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const ret = [];
        col.forEach(d => {
            if (d.sn === "tp") {
                d.ctl = wtype;
            }

            ret.push(d);
        });

        return ret;
    };

    const act = {
        "add": (v, h) => umd.update("station/add", {v: v}, h),
        "edit": (v, h) => umd.update("station/md", {v: [v]}, h),
    };

    if (umd.isFin("edit") || umd.isFin("add")) {
        return <HandView umd={umd} title={loc("l_255")} act={act} col={hCol()} ck={get_ck(umd.cur, umd.value, col)}/>;
    }

    if (umd.isFin("col")) {
        const list = [
            {sn: "station", name: loc("l_643"), fix: get_fix()},
        ];

        const hreturn = () => {
            load_col(setCol);
            umd.hreturn();
        };

        return <ColView hreturn={hreturn} title={loc("l_255")} subtitle={loc("l_221")} list={list} cur="station"/>;
    }

    if (umd.isFin("user")) {
        const hreturn = () => {
            umd.reload();
            umd.hreturn();
        };

        return <BindUser hreturn={hreturn} cur={umd.cur}/>;
    }

    if (umd.isFin("equip")) {
        const hreturn = () => {
            umd.reload();
            umd.hreturn();
        };

        return <BindEquip hreturn={hreturn} cur={umd.cur}/>;
    }

    const hDel = (val) => {
        if (no_del()) {
            return;
        }

        umd.update("station/rm", {k: obj_str(val, "sn")});
    };

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
            {name: loc("l_238"), key: 'e_opt', width: 230, frozen: true, formatter: (props) => {
                const d = props.row;
                return (
                    <div className="inline-flex">
                        <MCmd hcmd={() => umd.pact(null, d, "edit")} itype="edit" disabled={no_acc("kh")}/>
                        <MCmd hcmd={() => hDel(d)} itype="del" disabled={no_acc("kh")}/>
                        <MUser hcmd={() => umd.pact(null, d, "user")} title={loc("l_254")} num={obj_int(d, "user_num")} disabled={no_acc("kh")}/>
                        <MLink hcmd={() => umd.pact(null, d, "equip")} title={loc("l_145")} num={obj_int(d, "equip_num")} disabled={no_acc("kh")}/>
                    </div>
                );
            }},
        ];

        col.forEach(d => {
            if (d.sn === "tp") {
                tmp.push({name: d.name, key: d.sn, width: 200, formatter: (props) => {
                    const d = props.row;
                    if (is_empty(wtype)) {
                        return null;
                    }

                    const f = wtype.find(t => t.sn === d.tp);
                    if (!f) {
                        return null;
                    }

                    const t = f.sn;

                    if (t === "start") {
                        return <Chip cl="green" label={f.name} flag="S"/>;
                    }
                    else if (t === "end") {
                        return <Chip cl="blue" label={f.name} flag="E"/>;
                    }

                    return <Chip label={f.name}/>;
                }});
            } else {
                tmp.push({name: d.name, key: d.sn, width: 200});
            }

        });

        return tmp;
    };

    const getList = () => {
        if (is_empty(col)) {
            return null;
        }

        return col.map(d => d.sn);
    };

    const rowTempl = () => {
        const tmp = getList();
        if (is_empty(tmp)) {
            return null;
        }

        const v = {};
        tmp.forEach(k => v[k] = "1");

        return [v];
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn className="mr-4" hcmd={() => umd.pact(null, null, "col")} disabled={no_acc("kh")}>{loc("l_221")}</Btn>
            <KFile umd={umd} title={loc("l_255")} col={getList()} row={rowTempl()} hcmd={hImport} no_acc_in={no_acc("kh")}/>
            <Btn color="green" hcmd={() => umd.pact(null, null, "add")} className="ml-4" disabled={no_acc("kh")}>{loc("l_239")}</Btn>
        </div>
    );

    return (
        <div className="flex flex-col">
            <PanelFind left={loc("l_255")} right={<Right/>} hcmd={umd.setFilter}/>
            <GridTable high={high} col={getCol()} row={getRow} rowHeight={48}/>
        </div>
    );
};

export {StationView};
